//
//  SPMapDataManager.m
//  SPMapKit
//
//  Created by zhangyz on 2017/9/18.
//  Copyright © 2017年 zhangbo. All rights reserved.
//

#import "SPMapDataManager.h"



@implementation SPMapDataManager

+ (SPMapDataManager *) Instance
{
    static SPMapDataManager* pstObj = nil;
    @synchronized(self)
    {
        if(nil == pstObj)
        {
            pstObj = [[SPMapDataManager alloc] init];
            pstObj.tmpImageDic = [[NSMutableDictionary alloc]init];
            pstObj.dbImageDic = [[NSMutableDictionary alloc]init];
            pstObj->_serialQueue = dispatch_queue_create("writeMapToDB.serialQueue", DISPATCH_QUEUE_SERIAL);
        }
    }
    return pstObj;
}


//drawRect准备时，已经是非主线程
//获取图片
- (MapImageInfo *) getImageForMap:(MapImageInfo *)info
{
    
    //先看缓存
    MapImageInfo *tempImageInfo = nil;

    if ([_dbImageDic count])
    {
        tempImageInfo = [_dbImageDic objectForKey:info.urlStr];
        
        if (tempImageInfo)
        {
            return tempImageInfo;
        }
    }
    else
    {
        [self firstLoadMap:info];
    }

    
    
    //再看数据库
    
    //每次从数据库获取这个范围内的图片
    MapImagesPosiionRange *tempRange = [[MapImagesPosiionRange alloc]init];
    
    tempRange.startLevel             = info.level;
    tempRange.endLevel               = info.level;
    
    if (info.row > SP_MAP_LOAD_IMAGEROWCOUNT)
    {
        tempRange.startRow          = info.row - SP_MAP_LOAD_IMAGEROWCOUNT;
    }
    else
    {
        tempRange.startRow          = info.row;
    }
    
    if (info.row + SP_MAP_LOAD_IMAGEROWCOUNT < pow(2, info.level))
    {
        tempRange.endRow            = info.row + SP_MAP_LOAD_IMAGEROWCOUNT;
    }
    else
    {
        tempRange.endRow            = info.row;
    }
    
    if (info.column > SP_MAP_LOAD_IMAGECOLUMNCOUNT)
    {
        tempRange.startColumn       = info.column - SP_MAP_LOAD_IMAGECOLUMNCOUNT;
    }
    else
    {
        tempRange.startColumn       = info.column;
    }
    
    if (info.column + SP_MAP_LOAD_IMAGECOLUMNCOUNT < pow(2, info.level))
    {
        tempRange.endColumn         = info.column + SP_MAP_LOAD_IMAGECOLUMNCOUNT;
    }
    else
    {
        tempRange.endColumn         = info.column;
    }
    
    //查询数据库中一定范围
    NSMutableDictionary *tempMapsDic = [[SPMapDBInstance Instance] getMapsFromDB:tempRange];
    
    if ([tempMapsDic count] > 0)
    {
        @synchronized(_dbImageDic)
        {
            [_dbImageDic addEntriesFromDictionary:tempMapsDic];
        }
        if ([tempMapsDic objectForKey:info.urlStr])
        {
            tempImageInfo = [tempMapsDic objectForKey:info.urlStr];
            return tempImageInfo;
        }
    }
    
    
    
    //网络获取
    NSURL * url = [NSURL URLWithString:info.urlStr];
    
    NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
    if (imageData)
    {
        UIImage * tempImage = [[UIImage alloc] initWithData:imageData];
        //存本地缓存
        info.image = tempImage;
        
        [self saveNetToTmp:info];
        
    }
    
    return info;

}


//首次加载
- (void)firstLoadMap:(MapImageInfo *)info
{
    
    MapImagesPosiionRange *firstRange = [[MapImagesPosiionRange alloc]init];
    
    if (info.level > 1)
    {
        firstRange.startLevel       = info.level - 1;
    }
    else
    {
        firstRange.startLevel       = info.level;
    }
    
    if (info.level < 19)
    {
        firstRange.endLevel         = info.level + 1;
    }
    else
    {
        firstRange.endLevel         = info.level;
    }
    
    
    if (info.row > SP_MAP_FIRSTLOAD_IMAGEWIDTHCOUNT)
    {
        firstRange.startRow         = info.row - SP_MAP_FIRSTLOAD_IMAGEWIDTHCOUNT;
    }
    else
    {
        firstRange.startRow         = info.row;
    }
    
    if (info.row + SP_MAP_FIRSTLOAD_IMAGEWIDTHCOUNT < pow(2, info.level))
    {
        firstRange.endRow           = info.row + SP_MAP_FIRSTLOAD_IMAGEWIDTHCOUNT;
    }
    else
    {
        firstRange.endRow           = info.row;
    }
    
    if (info.column > SP_MAP_FIRSTLOAD_IMAGEWIDTHCOUNT)
    {
        firstRange.startColumn      = info.column - SP_MAP_FIRSTLOAD_IMAGEWIDTHCOUNT;
    }
    else
    {
        firstRange.startColumn      = info.column;
    }
    
    if (info.column + SP_MAP_FIRSTLOAD_IMAGEWIDTHCOUNT < pow(2, info.level))
    {
        firstRange.endColumn        = info.column + SP_MAP_FIRSTLOAD_IMAGEWIDTHCOUNT;
    }
    else
    {
        firstRange.endColumn        = info.column;
    }
    
    //查询数据库中一定范围
    NSMutableDictionary *tempMapsDic = [[SPMapDBInstance Instance] getMapsFromDB:firstRange];
    
    if ([[tempMapsDic allKeys] count] > 0)
    {
        @synchronized(_dbImageDic)
        {
            [_dbImageDic addEntriesFromDictionary:tempMapsDic];
        }
    }
}

//从网络获取成功，然后存到本地缓存，并在适当时机插入数据库
- (void) saveNetToTmp:(MapImageInfo *)info
{
    //保存到本地临时缓存
    @synchronized(_dbImageDic)
    {
        
        [_dbImageDic setObject:info forKey:info.urlStr];
        
        NSMutableDictionary *tempDic = [[NSMutableDictionary alloc]init];
        [tempDic setObject:info forKey:info.urlStr];
        //异步串行队列
        dispatch_async(_serialQueue, ^{
            [[SPMapDBInstance Instance] addMapsToDB:tempDic];
        });
        
    }
}


@end
